// Redis Toolkit 主入口文件

import 'reflect-metadata';

import { RedisClient } from './core/RedisClient';
import { CacheManager } from './managers/CacheManager';
import { SessionManager } from './managers/SessionManager';
import { QueueManager } from './managers/QueueManager';
import { CounterManager } from './managers/CounterManager';
import { SetManager } from './managers/SetManager';
import { LeaderboardManager } from './managers/LeaderboardManager';
import { RateLimitManager } from './managers/RateLimitManager';
import { LockManager } from './managers/LockManager';
import { PubSubManager } from './managers/PubSubManager';
import { BloomFilterManager } from './managers/BloomFilterManager';
import { MonitoringManager } from './managers/MonitoringManager';
import { SecurityManager } from './managers/SecurityManager';
import { BatchManager } from './managers/BatchManager';
import { DebugManager } from './managers/DebugManager';

import { RedisConfig, Logger, Middleware, RedisPlugin } from './types';

import { defaultLogger } from './utils/logger';

export interface RedisToolkitConfig extends RedisConfig {
  // 管理器配置
  cache?: any;
  session?: any;
  queue?: any;
  counter?: any;
  set?: any;
  leaderboard?: any;
  rateLimit?: any;
  lock?: any;
}

export class RedisToolkit {
  private client: RedisClient;
  private logger: Logger;
  private plugins: Map<string, RedisPlugin> = new Map();

  // 管理器实例
  public readonly cache: CacheManager;
  public readonly session: SessionManager;
  public readonly queue: QueueManager;
  public readonly counter: CounterManager;
  public readonly set: SetManager;
  public readonly leaderboard: LeaderboardManager;
  public readonly rateLimit: RateLimitManager;
  public readonly lock: LockManager;
  public readonly pubsub: PubSubManager;
  public readonly bloom: BloomFilterManager;
  public readonly monitoring: MonitoringManager;
  public readonly security: SecurityManager;
  public readonly batch: BatchManager;
  public readonly debug: DebugManager;

  constructor(config: RedisToolkitConfig) {
    this.logger = config.logger ?? defaultLogger.createChild('RedisToolkit');

    // 初始化Redis客户端
    this.client = new RedisClient(config);

    // 初始化管理器
    this.cache = new CacheManager(this.client);
    this.session = new SessionManager(this.client, config.session);
    this.queue = new QueueManager(this.client, config.queue);
    this.counter = new CounterManager(this.client);
    this.set = new SetManager(this.client);
    this.leaderboard = new LeaderboardManager(this.client, config.leaderboard);
    this.rateLimit = new RateLimitManager(this.client);
    this.lock = new LockManager(this.client);
    this.pubsub = new PubSubManager(this.client);
    this.bloom = new BloomFilterManager(this.client);
    this.monitoring = new MonitoringManager(this.client);
    this.security = new SecurityManager(this.client);
    this.batch = new BatchManager(this.client);
    this.debug = new DebugManager(this.client);

    this.logger.info('RedisToolkit initialized successfully');
  }

  /**
   * 连接到Redis
   */
  async connect(): Promise<void> {
    await this.client.connect();
    this.logger.info('RedisToolkit connected to Redis');
  }

  /**
   * 断开连接
   */
  async disconnect(): Promise<void> {
    await this.client.disconnect();
    this.logger.info('RedisToolkit disconnected from Redis');
  }

  /**
   * 获取原始Redis客户端
   */
  getClient(): RedisClient {
    return this.client;
  }

  /**
   * 添加中间件
   */
  use(middleware: Middleware): void {
    this.client.use(middleware);
  }

  /**
   * 安装插件
   */
  install(plugin: RedisPlugin): void {
    if (this.plugins.has(plugin.name)) {
      throw new Error(`Plugin ${plugin.name} is already installed`);
    }

    try {
      plugin.install(this);
      this.plugins.set(plugin.name, plugin);
      this.logger.info(`Plugin ${plugin.name} v${plugin.version} installed`);
    } catch (error) {
      this.logger.error(`Failed to install plugin ${plugin.name}`, { error });
      throw error;
    }
  }

  /**
   * 卸载插件
   */
  uninstall(pluginName: string): void {
    const plugin = this.plugins.get(pluginName);

    if (!plugin) {
      throw new Error(`Plugin ${pluginName} is not installed`);
    }

    try {
      plugin.uninstall();
      this.plugins.delete(pluginName);
      this.logger.info(`Plugin ${pluginName} uninstalled`);
    } catch (error) {
      this.logger.error(`Failed to uninstall plugin ${pluginName}`, { error });
      throw error;
    }
  }

  /**
   * 获取已安装的插件列表
   */
  getInstalledPlugins(): string[] {
    return Array.from(this.plugins.keys());
  }

  /**
   * 健康检查
   */
  async healthCheck(): Promise<any> {
    const clientHealth = await this.client.healthCheck();

    return {
      ...clientHealth,
      toolkit: {
        version: '1.0.0',
        managers: {
          cache: 'active',
          session: 'active',
          queue: 'active',
          counter: 'active',
          set: 'active',
          leaderboard: 'active',
          rateLimit: 'active',
          lock: 'active',
        },
        plugins: this.getInstalledPlugins(),
      },
    };
  }

  /**
   * 获取统计信息
   */
  async getStats(): Promise<any> {
    const [cacheStats, sessionStats, connectionStats] = await Promise.all([
      this.cache.getStats().catch(() => null),
      this.session.getStats().catch(() => null),
      Promise.resolve(this.client.getConnectionStats()),
    ]);

    return {
      connection: connectionStats,
      cache: cacheStats,
      session: sessionStats,
      timestamp: new Date(),
    };
  }

  /**
   * 执行原始Redis命令
   */
  async execute<T = any>(command: string, ...args: any[]): Promise<T> {
    return this.client.execute<T>(command, ...args);
  }

  /**
   * 创建管道
   */
  pipeline(): any {
    return this.client.pipeline();
  }

  /**
   * 创建事务
   */
  multi(): any {
    return this.client.multi();
  }
}

// 导出类型和工具
export * from './types';
export * from './utils/logger';
export * from './utils/serializer';
export * from './utils/keyGenerator';

// 导出管理器
export { CacheManager } from './managers/CacheManager';
export { SessionManager } from './managers/SessionManager';
export { QueueManager } from './managers/QueueManager';
export { CounterManager } from './managers/CounterManager';
export { SetManager } from './managers/SetManager';
export { LeaderboardManager } from './managers/LeaderboardManager';
export { RateLimitManager } from './managers/RateLimitManager';
export { LockManager } from './managers/LockManager';
export { PubSubManager } from './managers/PubSubManager';
export { BloomFilterManager } from './managers/BloomFilterManager';
export { MonitoringManager } from './managers/MonitoringManager';
export { SecurityManager } from './managers/SecurityManager';
export { BatchManager } from './managers/BatchManager';
export { DebugManager } from './managers/DebugManager';

// 导出核心类
export { RedisClient } from './core/RedisClient';
export { BaseManager } from './core/BaseManager';

// 默认导出
export default RedisToolkit;

/**
 * 创建RedisToolkit实例的工厂函数
 */
export function createRedisToolkit(config: RedisToolkitConfig): RedisToolkit {
  return new RedisToolkit(config);
}

/**
 * 创建内存Redis实例（用于测试）
 */
export function createInMemoryRedisToolkit(): RedisToolkit {
  // 这里可以集成redis-mock或其他内存Redis实现
  // 简化实现，返回普通实例
  return new RedisToolkit({
    host: 'localhost',
    port: 6379,
    autoSerialize: true,
  });
}
